<?php
namespace App\Api\Controllers\DevicePay;


use App\Api\Controllers\Config\PayWaysController;
use App\Api\Controllers\Merchant\AliFqPayController;
use App\Api\Controllers\Merchant\AlipayFqOrderController;
use App\Api\Controllers\Merchant\OrderController;
use App\Api\Controllers\Merchant\PayBaseController;
use App\Models\AlipayHbrate;
use App\Models\Device;
use App\Models\Merchant;
use App\Models\MerchantStore;
use App\Models\MqttConfig;
use App\Models\Order;
use App\Models\RefundOrder;
use App\Models\Store;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

/**
 * 扫码设备支付接口
 * Class IndexController
 * @package App\Api\Controllers\DevicePay
 */
class FqIndexController extends BaseController
{

    //扫一扫收款
    public function fq_scan_pay(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $total_amount = $request->get('total_amount'); //金额
            $total_amount = number_format($total_amount, 2, '.', '');
            $shop_price = $request->get('shop_price', $total_amount);
            $hb_fq_num = (int)$request->get('hb_fq_num', '6'); //花呗分期数
            $hb_fq_seller_percent = $request->get('hb_fq_seller_percent', '0'); //商家承担手续费传入100，用户承担手续费传入0$hb_fq_seller_percent=0;
            $buyer_user = $request->get('buyer_user', '');
            $buyer_phone = $request->get('buyer_phone', '');
            $ways_source = $request->get('ways_source', ''); //支付通道
            $config_id = $request->get('config_id', '');
            $auth_code = $request->get('auth_code', '');
            $merchant_id = $request->get('merchant_id', '');
            $merchant_name = $request->get('merchant_name', '');
            $store_id = $request->get('store_id', '');
            $shop_name = $request->get('shop_name', '分期商品');

            $check_data = [
                'total_amount' => '付款金额',
                'device_id' => '设备编号',
                'device_type' => '设备类型',
                'store_id' => '门店id',
                'merchant_id' => '收银员id'
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $check
                ];
                return $this->return_data($err);
            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'result_code' => '',
                'result_msg' => '',
                'store_id' => $store_id,
                'ways_source' => '',
                'ways_source_desc' => '',
                'total_amount' => $total_amount
            ];

            if ($shop_name == "undefined") {
                $shop_name = "分期商品";
            }

            $data = [
                'merchant_id' => $merchant_id,
                'merchant_name' => $merchant_name,
                'shop_name' => $shop_name,
                'total_amount' => $total_amount,
                'shop_price' => $shop_price,
                'hb_fq_num' => $hb_fq_num,
                'hb_fq_seller_percent' => $hb_fq_seller_percent,
                'buyer_user' => $buyer_user,
                'buyer_phone' => $buyer_phone,
                'ways_source' => $ways_source,
                'config_id' => $config_id,
                'auth_code' => $auth_code,
                'store_id' => $store_id
            ];
            $pay_obj = new AliFqPayController();
            $scan_pay_public = $pay_obj->fq_pay_public($data);
            $tra_data_arr = json_decode($scan_pay_public, true);
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message'],
                    'result_code' => 'FALL',
                    'result_msg' => $tra_data_arr['message']
                ];
                return $this->return_data($err);
            }

            //B扫C
            if ($auth_code) {
                //用户支付成功
                if ($tra_data_arr['pay_status'] == '1') {
                    //微信，支付宝支付凭证
                    $re_data['result_code'] = 'SUCCESS';
                    $re_data['result_msg'] = '支付成功';
                    $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                    $re_data['out_transaction_id'] = $tra_data_arr['data']['out_trade_no'];
                    $re_data['pay_time'] = date('YmdHis', strtotime(isset($tra_data_arr['data']['pay_time']) ? $tra_data_arr['data']['pay_time'] : time()));
                    $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];
                } //正在支付
                elseif ($tra_data_arr['pay_status'] == '2') {
                    $re_data['result_code'] = 'USERPAYING';
                    $re_data['result_msg'] = '用户正在支付';
                    $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                } //其他错误
                else {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = $tra_data_arr['message'];
                }
            } //C扫B
            else {
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['code_url'] = $tra_data_arr['data']['code_url'];
            }

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    //查询订单号状态
    public function fq_order_query(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $other_no = isset($data['other_no']) ? $data['other_no'] : '';
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];

            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $config_id = isset($data['config_id']) ? $data['config_id'] : "";

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'other_no' => $other_no,
                'store_id' => $store_id
            ];

            $data = [
                'out_trade_no' => $out_trade_no,
                'other_no' => $other_no,
                'store_id' => $store_id,
                'ways_type' => '',
                'config_id' => $config_id
            ];

            $order_obj = new OrderController();
            $return = $order_obj->hb_order_foreach_public($data);

            $tra_data_arr = json_decode($return, true);
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message']
                ];
                return $this->return_data($err);
            }

            //用户支付成功
            if ($tra_data_arr['pay_status'] == '1') {
                //微信，支付宝支付凭证
                $re_data['result_code'] = 'SUCCESS';
                $re_data['result_msg'] = '支付成功';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['out_transaction_id'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['pay_time'] = date('YmdHis', strtotime($tra_data_arr['data']['pay_time']));
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];;
                $re_data['pay_amount'] = isset($tra_data_arr['data']['pay_amount']) ? $tra_data_arr['data']['pay_amount'] : "";
                $re_data['total_amount'] = isset($tra_data_arr['data']['total_amount']) ? $tra_data_arr['data']['total_amount'] : "";
                $re_data['other_no'] = isset($tra_data_arr['data']['other_no']) ? $tra_data_arr['data']['other_no'] : "";
            } //正在支付
            elseif ($tra_data_arr['pay_status'] == '2') {
                $re_data['result_code'] = 'USERPAYING';
                $re_data['result_msg'] = '用户正在支付';
                $re_data['out_trade_no'] = $out_trade_no;
            } //其他错误
            else {
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = $tra_data_arr['message'];
            }

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    //查询这个门店获得前端展示的服务费多少
    public function fq_query_rate(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $store_id = $request->get('store_id', '');
            $hb_fq_seller_percent = $request->get('hb_fq_seller_percent', 0);
            $shop_price = $request->get('shop_price', '100');
            $hb_fq_num = $request->get('hb_fq_num', '');

            $AlipayHbrate = AlipayHbrate::where('store_id', $store_id)->first();
            //用户承担
            if ($hb_fq_seller_percent == 0) {
                $xy_ra_3 = 2.3;
                $xy_ra_6 = 4.5;
                $xy_ra_12 = 7.5;
                $base_ra_3 = 2.3;
                $base_ra_6 = 4.5;
                $base_ra_12 = 7.5;

                //商户设置的费率
                if ($AlipayHbrate) {
                    $xy_ra_3 = $AlipayHbrate->hb_fq_num_3;
                    $xy_ra_6 = $AlipayHbrate->hb_fq_num_6;
                    $xy_ra_12 = $AlipayHbrate->hb_fq_num_12;
                }

                $fqfwf_all_3 = ($xy_ra_3 * $shop_price) / 100; //界面显示总服务费
                $total_amount_3 = $fqfwf_all_3 + $shop_price; //界面显示总付款金额
                $total_amount_3_h = ($fqfwf_all_3 + $shop_price) / 3; //每期还款
                $pay_total_amount_3 = $total_amount_3 / (1 + ($base_ra_3 / 100)); //传给支付宝

                $hb_fq_sxf_3 = $pay_total_amount_3 - $shop_price; //转出来的部分
                $fqfwf_all_6 = ($xy_ra_6 * $shop_price) / 100; //界面显示总服务费
                $total_amount_6 = $fqfwf_all_6 + $shop_price; //界面显示总付款金额
                $total_amount_6_h = ($fqfwf_all_6 + $shop_price) / 6; //每期还款
                $pay_total_amount_6 = $total_amount_6 / (1 + ($base_ra_6 / 100)); //传给支付宝
                $hb_fq_sxf_6 = $pay_total_amount_6 - $shop_price; //转出来的部分

                $fqfwf_all_12 = ($xy_ra_12 * $shop_price) / 100; //界面显示总服务费
                $total_amount_12 = $fqfwf_all_12 + $shop_price; //界面显示总付款金额
                $total_amount_12_h = ($fqfwf_all_12 + $shop_price) / 12; //每期还款
                $pay_total_amount_12 = $total_amount_12 / (1 + ($base_ra_12 / 100)); //传给支付宝
                $hb_fq_sxf_12 = $pay_total_amount_12 - $shop_price; //转出来的部分

                if ($hb_fq_num == 3) {
                    $fq_data = [
                        'hb_fq_num' => 3,
                        'hb_fq_seller_percent' => $hb_fq_seller_percent,
                        'shop_price' => $shop_price,
                        'hb_mq_h' => number_format($total_amount_3_h, 2, '.', ''),
                        'hb_fq_sxf' => number_format($fqfwf_all_3, 2, '.', ''),
                        'total_amount' => number_format($total_amount_3, 2, '.', '')
                    ];
                } elseif ($hb_fq_num == 6) {
                    $fq_data = [
                        'hb_fq_num' => 6,
                        'hb_fq_seller_percent' => $hb_fq_seller_percent,
                        'shop_price' => $shop_price,
                        'hb_mq_h' => number_format($total_amount_6_h, 2, '.', ''),
                        'hb_fq_sxf' => number_format($fqfwf_all_6, 2, '.', ''),
                        'total_amount' => number_format($total_amount_6, 2, '.', '')
                    ];
                } elseif ($hb_fq_num == 12) {
                    $fq_data = [
                        'hb_fq_num' => 12,
                        'hb_fq_seller_percent' => $hb_fq_seller_percent,
                        'shop_price' => $shop_price,
                        'hb_mq_h' => number_format($total_amount_12_h, 2, '.', ''),
                        'hb_fq_sxf' => number_format($fqfwf_all_12, 2, '.', ''),
                        'total_amount' => number_format($total_amount_12, 2, '.', '')
                    ];
                } else {
                    $fq_data = [
                        [
                            'hb_fq_num' => 3,
                            'hb_fq_seller_percent' => $hb_fq_seller_percent,
                            'shop_price' => $shop_price,
                            'hb_mq_h' => number_format($total_amount_3_h, 2, '.', ''),
                            'hb_fq_sxf' => number_format($fqfwf_all_3, 2, '.', ''),
                            'total_amount' => number_format($total_amount_3, 2, '.', '')
                        ],
                        [
                            'hb_fq_num' => 6,
                            'hb_fq_seller_percent' => $hb_fq_seller_percent,
                            'shop_price' => $shop_price,
                            'hb_mq_h' => number_format($total_amount_6_h, 2, '.', ''),
                            'hb_fq_sxf' => number_format($fqfwf_all_6, 2, '.', ''),
                            'total_amount' => number_format($total_amount_6, 2, '.', '')
                        ],
                        [
                            'hb_fq_num' => 12,
                            'hb_fq_seller_percent' => $hb_fq_seller_percent,
                            'shop_price' => $shop_price,
                            'hb_mq_h' => number_format($total_amount_12_h, 2, '.', ''),
                            'hb_fq_sxf' => number_format($fqfwf_all_12, 2, '.', ''),
                            'total_amount' => number_format($total_amount_12, 2, '.', '')
                        ]
                    ];
                }
            } else {
                //买家自己承担
                $xy_ra_3 = 0;
                $xy_ra_6 = 0;
                $xy_ra_12 = 0;

                if ($hb_fq_num == 3) {
                    $fq_data = [
                        'hb_fq_num' => 3,
                        'hb_fq_seller_percent' => $hb_fq_seller_percent,
                        'shop_price' => $shop_price,
                        'hb_mq_h' => number_format(($shop_price + ($shop_price * $xy_ra_3) / 100) / 3, 2, '.', ''),
                        'hb_fq_sxf' => number_format(($shop_price * $xy_ra_3) / 100, 2, '.', ''),
                        'total_amount' => number_format(($shop_price + ($shop_price * $xy_ra_3) / 100), 2, '.', '')
                    ];
                } elseif ($hb_fq_num == 6) {
                    $fq_data = [
                        'hb_fq_num' => 6,
                        'hb_fq_seller_percent' => $hb_fq_seller_percent,
                        'shop_price' => $shop_price,
                        'hb_mq_h' => number_format(($shop_price + ($shop_price * $xy_ra_6) / 100) / 6, 2, '.', ''),
                        'hb_fq_sxf' => number_format(($shop_price * $xy_ra_6) / 100, 2, '.', ''),
                        'total_amount' => number_format(($shop_price + ($shop_price * $xy_ra_6) / 100), 2, '.', '')
                    ];
                } elseif ($hb_fq_num == 12) {
                    $fq_data = [
                        'hb_fq_num' => 12,
                        'hb_fq_seller_percent' => $hb_fq_seller_percent,
                        'shop_price' => $shop_price,
                        'hb_mq_h' => number_format(($shop_price + ($shop_price * $xy_ra_12) / 100) / 12, 2, '.', ''),
                        'hb_fq_sxf' => number_format(($shop_price * $xy_ra_12) / 100, 2, '.', ''),
                        'total_amount' => number_format(($shop_price + ($shop_price * $xy_ra_12) / 100), 2, '.', '')
                    ];
                } else {
                    $fq_data = [
                        [
                            'hb_fq_num' => 3,
                            'hb_fq_seller_percent' => $hb_fq_seller_percent,
                            'shop_price' => $shop_price,
                            'hb_mq_h' => number_format(($shop_price + ($shop_price * $xy_ra_3) / 100) / 3, 2, '.', ''),
                            'hb_fq_sxf' => number_format(($shop_price * $xy_ra_3) / 100, 2, '.', ''),
                            'total_amount' => number_format(($shop_price + ($shop_price * $xy_ra_3) / 100), 2, '.', '')
                        ],
                        [
                            'hb_fq_num' => 6,
                            'hb_fq_seller_percent' => $hb_fq_seller_percent,
                            'shop_price' => $shop_price,
                            'hb_mq_h' => number_format(($shop_price + ($shop_price * $xy_ra_6) / 100) / 6, 2, '.', ''),
                            'hb_fq_sxf' => number_format(($shop_price * $xy_ra_6) / 100, 2, '.', ''),
                            'total_amount' => number_format(($shop_price + ($shop_price * $xy_ra_6) / 100), 2, '.', '')
                        ],
                        [
                            'hb_fq_num' => 12,
                            'hb_fq_seller_percent' => $hb_fq_seller_percent,
                            'shop_price' => $shop_price,
                            'hb_mq_h' => number_format(($shop_price + ($shop_price * $xy_ra_12) / 100) / 12, 2, '.', ''),
                            'hb_fq_sxf' => number_format(($shop_price * $xy_ra_12) / 100, 2, '.', ''),
                            'total_amount' => number_format(($shop_price + ($shop_price * $xy_ra_12) / 100), 2, '.', '')
                        ]
                    ];
                }
            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功'
            ];

            return $this->data_return($re_data, $fq_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    //分期退款
    public function fq_refund(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $config_id = isset($data['config_id']) ? $data['config_id'] : "";
            $out_trade_no = $request->get('out_trade_no', '');
            $refund_amount = $request->get('refund_amount', '');
            $refund_no = $request->get('refund_no', '');
            $refund_no = $out_trade_no . time();
            $merchant_id = $request->get('merchant_id', '');

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'store_id' => $store_id
            ];

            $data = [
                'merchant_id' => $merchant_id,
                'out_trade_no' => $out_trade_no,
                'refund_amount' => $refund_amount,
                'refund_no' => $refund_no
            ];
            $obj = new AlipayFqOrderController();
            $return = $obj->refund_public($data);
            $tra_data_arr = json_decode($return, true);
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message']
                ];
                return $this->return_data($err);
            }

            $re_data['result_code'] = 'SUCCESS';
            $re_data['result_msg'] = '退款成功';

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


}
